package bingosoft.metro.code.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bingosoft.components.base.service.BaseClass;
import bingosoft.metro.code.model.DbColumnModel;
import bingosoft.metro.code.model.DbTableModel;
import leap.lang.Strings;

/**
 * @author Feily
 * @功能描述 数据库服务接口类
 * @创建时间 2017-09-22
 */
public class DbDatabaseService extends BaseClass implements IDatabaseService {
	/**
	 * 构建函数
	 */
	public DbDatabaseService() {
		this.setLogClass(this.getClass());
	}
	
	@Override
	public DbTableModel getTable(String tableName){
		this.logMethodCalled("getTable");
		this.logParamValue("tableName", tableName);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("tableName", tableName);
		
		String sql = this.getSqlKey("code-queryTables");
		DbTableModel table = DbTableModel.<DbTableModel>query(sql).params(params).firstOrNull();		
		return table;
	}

	@Override
	public List<DbTableModel> queryAllTables(){
		this.logMethodCalled("queryAllTables");
		
		// 查询结果
		String sql = this.getSqlKey("code-queryTables");
		List<DbTableModel> list = DbTableModel.<DbTableModel>query(sql).list();
		return list;
	}
	
	@Override
	public List<DbColumnModel> queryColumns(String tableName){
		this.logMethodCalled("queryColumns");
		this.logParamValue("tableName", tableName);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("tableName", tableName);
		
		// 查询结果
		String sql = this.getSqlKey("code-queryColumns");
		List<DbColumnModel> list = DbColumnModel.<DbColumnModel>query(sql).params(params).list();
		return list;
	}
	
	protected String getSqlKey(String sqlKey) {
		String dbName = "";
		if(DbTableModel.db().isPostgreSQL()){
			dbName = "postgreSql";
		}else if(DbTableModel.db().isOracle()){
			dbName = "oracle";
		}else if(DbTableModel.db().isSqlServer()) {
			dbName = "sqlServer";
		}
		
		if(!Strings.isEmpty(dbName)){
			sqlKey = sqlKey + "$" + dbName;
		}
		return sqlKey;
	}
}
